package com.xmqsfsky1017.skysrf.utils;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;


public class Cycle <T> {
    private int length;
	private List<T> objs;
    private int currentIdx;
	
	public Cycle(T... args) {
		objs=Arrays.asList(args);
		length=objs.size();
		currentIdx=0;
	}
	
    public Cycle<T> add(int x){
		currentIdx+=x;
		currentIdx = getRightIdx(currentIdx);
		return this;
	}
	
	public Cycle<T> sub(int x){
		currentIdx-=x;
		currentIdx = getRightIdx(currentIdx);
		return this;
	}
	
	public T get(){
		return objs.get(currentIdx);
	}
	
	public T get(int x) {
		if (x < 0 || x >= length) {
            throw new IndexOutOfBoundsException(
			    "索引超出范围：" + x + "，有效范围是 0 到 " + (length - 1)
						);
		}
		return objs.get(x);
	}
	
	public Cycle<T> set(T obj){
        if (!objs.contains(obj)) {
			throw new IllegalArgumentException("需跳转对象不在循环中");
		}
		currentIdx=objs.indexOf(obj);
		return this;
	}
	
	public Cycle<T> set(int x) {
	    if (x < 0 || x >= length) {
            throw new IndexOutOfBoundsException(
			    "索引超出范围：" + x + "，有效范围是 0 到 " + (length - 1)
						);
		}
		currentIdx=x;
		return this;
	}
	
	private int getRightIdx(int idx) {
		return (idx%length+length)%length;
	}
	
}	